<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form @submit="handleSubmit" :form="form">
      <a-row>
        <a-col :span="12">
          <a-form-item
            label="终端类型"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <a-radio-group
              name="clientType"
              @change="radioChange"
              v-decorator="[
                'clientType',
                {rules: [{ required: true, message: '请选择终端类型' }]}
              ]">
              <a-radio :value="1">安卓</a-radio>
              <a-radio :value="2">IOS</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="类型"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <a-select
              style="min-width: 120px;max-width:200px"
              name="linkType"
              @select="selectChange"
              v-decorator="[
                'linkType',
                {rules: [{ required: true, message: '请选择类型' }]}
              ]">
              <a-select-option :value="0">外链</a-select-option>
              <a-select-option :value="1">内链</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="广告图"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <upload-image
              :imageUrl="picUrl"
              :imageType="3"
              @uploadImage="uploadImage"
              name="picUrl"
              v-decorator="[
                'picUrl',
                {
                  rules: [{ required: true, message: '请上传图片' }],
                },
              ]"
            ></upload-image>
          </a-form-item></a-col>
        <a-col :span="12">
          <a-form-item
            label="广告位"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <a-select
              style="min-width: 120px;max-width:200px"
              name="postion"
              placeholder="请选择广告位"
              v-decorator="[
                'postion',
                {rules: [{ required: true, message: '请选择类型' }]}
              ]">
              <a-select-option :value="po.id" v-for="(po, index) in positionList" :key="index">{{ po.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="状态"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <a-radio-group
              name="flag"
              v-decorator="[
                'flag',
                {rules: [{ required: true, message: '请选择终端类型' }]}
              ]">
              <a-radio :value="1">上线</a-radio>
              <a-radio :value="0">下线</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="链接地址"
            :labelCol="{lg: {span: 7}, sm: {span: 7}}"
            :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
            <div @click="linkUrlClick">
              <a-input
                style="min-width:300px"
                :disabled="disabled"
                v-decorator="[
                  'linkUrl',
                  {rules: [{ required: true, message: '请输入链接地址' }]}
                ]"
                name="linkUrl"
                placeholder="请输入链接地址" />
            </div>

          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item
        :wrapperCol="{ span: 24 }"
        style="text-align: center;margin:20px 0;"
      >
        <a-button style="min-width:120px" htmlType="submit" :loading="confirmLoading" type="primary">提交</a-button>
        <a-button style="margin-left: 15px;min-width:120px" @click="$router.go(-1)">返回</a-button>
      </a-form-item>
    </a-form>
    <code-model ref="modal" @ok="handleOk"></code-model>
  </a-card>
</template>

<script>
import UploadImage from '@/viewsVue/commit/UploadImage'
import CodeModel from '../modules/CodeModel'
import { mapActions } from 'vuex'
export default {
  name: 'AdsForm',
  components: {
    UploadImage,
    CodeModel
  },
  data () {
    return {
      disabled: false,
      appTypeId: '',
      packageName: '',
      linkType: 0,
      appId: '',
      linkUrl: '',
      picUrl: '',
      positionList: [],
      confirmLoading: false,
      // form
      form: this.$form.createForm(this)

    }
  },
  mounted () {
    if (this.$route.params.id) {
      this.ApiDetail()
    } else {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          clientType: 1,
          linkType: 0,
          flag: 1
        })
        this.ApiPosiList(this.form.getFieldValue('linkType'))
      })
      if (this.form.getFieldValue('linkType') === 1) {
        this.disabled = true
      } else {
        this.disabled = false
      }
    }
  },
  methods: {
    ...mapActions(['AdsPositionList', 'AdsAdd', 'AdsEdit', 'GetAdsInfo', 'GetInto']),
    ApiDetail () { // 广告详情
      this.GetAdsInfo({ id: this.$route.params.id })
        .then((res) => {
          if (res.status === 200 || res.status === '200') {
            if (res.data.picUrl) {
              this.picUrl = res.data.picUrl
            }
            if (res.data.linkUrl) {
              this.linkUrl = res.data.linkUrl
            }
            if (res.data.linkType === 1) {
              this.disabled = true
            } else {
              this.disabled = false
            }
            if (res.data.linkArg) {
              this.appId = res.data.linkArg
              this.ApiIntoDetail(res.data.linkArg)
            }
            if (String(res.data.linkType)) {
              this.linkType = res.data.linkType
            }
            this.form = this.$form.createForm(this, {
              mapPropsToFields: () => {
                return {
                  clientType: this.$form.createFormField({
                    value: String(res.data.clientType) ? res.data.clientType : 1
                  }),
                  linkType: this.$form.createFormField({
                    value: String(res.data.linkType) ? res.data.linkType : 1
                  }),
                  picUrl: this.$form.createFormField({
                    value: res.data.picUrl || ''
                  }),
                  postion: this.$form.createFormField({
                    value: res.data.postion
                  }),
                  flag: this.$form.createFormField({
                    value: String(res.data.flag) ? res.data.flag : 1
                  }),
                  linkUrl: this.$form.createFormField({
                    value: String(res.data.linkType) === '1' ? '' : res.data.linkUrl
                  })
                }
              } })
            this.ApiPosiList(res.data.clientType)
          } else {
            this.requestFailed(res)
          }
        })
        .catch(err => this.requestFailed(err))
    },
    ApiIntoDetail (id) {
      this.GetInto({
        id: id
      })
        .then((res) => {
          if (res.status === 200 || res.status === '200') {
            this.appTypeId = res.data.appTypePath.substring(1, 2)
            if (res.data.packageName) {
              this.packageName = res.data.packageName
              this.form.setFieldsValue({ 'linkUrl': res.data.packageName })
            }
          } else {
            this.requestFailed(res)
          }
        })
        .catch(err => this.requestFailed(err))
    },
    ApiPosiList (clientType) { // 广告位列表
      this.AdsPositionList({
        clientType: clientType
      })
        .then((res) => {
          if (res.status === 200 || res.status === '200') {
            if (res.data.list && res.data.list.length !== 0) {
              this.positionList = res.data.list
            }
          } else {
            this.requestFailed(res)
          }
        })
        .catch(err => this.requestFailed(err))
    },
    uploadImage (val) { // 图片上传成功显示
      if (val) {
        this.picUrl = val.img
        this.$nextTick(() => {
          this.form.setFieldsValue({ 'picUrl': val.img })
        })
      }
    },
    selectChange (val) {
      if (this.linkType === val) {
        this.form.setFieldsValue({ 'linkUrl': this.linkUrl })
      } else {
        this.form.setFieldsValue({ 'linkUrl': '' })
      }
      if (val === 1) {
        if (this.linkType === 1 && this.packageName) {
          this.form.setFieldsValue({ 'linkUrl': this.packageName })
          this.disabled = true
        } else {
          this.disabled = false
        }
      } else {
        this.disabled = false
      }
    },
    radioChange (val) { // 终端类型切换
      this.ApiPosiList(val.target.value)
    },
    linkUrlClick () { // 点击链接地址
      if (this.form.getFieldValue('linkType') === 1) {
        this.$refs.modal.code({
          appId: this.appId,
          appTypeId: this.appTypeId
        })
      }
    },
    handleOk (val) {
      if (val && JSON.stringify(val) !== '{}' && val.packageName) {
        this.form.setFieldsValue({ 'linkUrl': val.packageName })
        this.appId = val.appId
        this.packageName = val.packageName
        this.disabled = true
      } else {
        this.disabled = false
      }
    },
    // handler
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          var linkUrl = ''
          var linkArg = ''
          if (values.linkType === 1) {
            linkUrl = ''
            linkArg = this.appId
          } else {
            linkArg = ''
            linkUrl = values.linkUrl
          }
          if (this.$route.params.id) {
            this.AdsEdit({
              id: this.$route.params.id,
              clientType: values.clientType,
              postion: values.postion,
              picUrl: values.picUrl,
              flag: values.flag,
              linkType: values.linkType,
              linkUrl: linkUrl || '',
              linkArg: linkArg || ''
            })
              .then((res) => this.submitSuccess(res))
              .catch(err => this.requestFailed(err))
          } else {
            this.AdsAdd({
              clientType: values.clientType,
              postion: values.postion,
              picUrl: values.picUrl,
              flag: values.flag,
              linkType: values.linkType,
              linkUrl: linkUrl || '',
              linkArg: linkArg || ''
            })
              .then((res) => this.submitSuccess(res))
              .catch(err => this.requestFailed(err))
          }
        }
      })
    },
    submitSuccess (res) {
      if (res.status === 200 || res.status === '200') {
        var mess = ''
        if (this.$route.params.id) {
          mess = '编辑成功'
        } else {
          mess = '新增成功'
        }
        this.$notification['success']({
          message: '成功',
          description: mess,
          duration: 4
        })
      } else {
        this.requestFailed(res)
      }
      setTimeout(() => {
        this.confirmLoading = false
      }, 1000)
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      setTimeout(() => {
        this.confirmLoading = false
      }, 1000)
    }
  }
}
</script>
